<template>
  <div>
    <Headline
      :headline1="$t('m.SystemManagement') + '  /  '"
      :headline2="$t('m.DataDictionary')"
    />
    <a-card>
      <a-input-search
        v-model="forminitial.key"
        style="width: 200px; margin-right: 20px"
        :placeholder="$t('m.CategoryKeywords')"
        enter-button
        @search="onSearch"
      />
      <a-button
        type="primary"
        icon="plus"
        style="margin-right: 20px"
        @click="addClassify"
        v-if="isTrue('sys:dictionaries:addtype')"
      >
        {{ $t("m.AddCategory") }}
      </a-button>
      <!-- <a-button type="primary" icon="delete"> 删除分类 </a-button> -->
      <a-table
        size="small"
        style="margin-top: 30px"
        :columns="columns"
        :rowKey="(record, i) => i"
        :data-source="data"
        :pagination="false"
        bordered
      >
        <div slot-scope="text, tags, i" slot="del">
          <a-button
            icon="zoom-in"
            style="margin-right: 15px"
            type="primary"
            @click="showItem(text, tags, i)"
          >
            {{ $t("m.Examine") }}</a-button
          >
          <a-button
              icon="edit"
              style="margin-right: 15px"
              type="primary"
              @click="editItem(text, tags, i)"
          >
            {{ $t("m.Modification") }}</a-button
          >
          <a-button
            icon="delete"
            type="danger"
            @click="delItem(text, tags, i)"
            v-if="isTrue('sys:dictionaries:deltype')"
          >
            {{ $t("m.Delete") }}</a-button
          >
        </div>
      </a-table>
      <a-pagination
        style="margin-top: 20px"
        show-size-changer
        :default-current="1"
        :total="total"
        @change="Pages"
        :pageSizeOptions="['5', '10', '30', '40']"
        @showSizeChange="onShowSizeChange"
        class="pages"
      />
    </a-card>
    <a-modal
      :title="$t('m.AddCategory')"
      :visible="visible"
      @cancel="handleCancel"
      :footer="null"
    >
      <a-form
        :form="form"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 12 }"
        @submit="handleSubmit"
      >
        <a-form-item :label="$t('m.DataDictionaryNumber')">
          <a-input
            v-decorator="[
              'code',
              {
                rules: [{ required: true, message: '请输入字典编号' }],
              },
            ]"
          />
        </a-form-item>
        <a-form-item :label="$t('m.DataDictionaryName')">
          <a-input
            v-decorator="[
              'name',
              {
                rules: [{ required: true, message: '请输入字典名称' }],
              },
            ]"
          />
        </a-form-item>
        <!-- <a-form-item :label="$t('m.CategoryNumber')">
          <a-input
            v-decorator="[
              'parentCode',
              {
                rules: [{ required: true, message: 'Please input your note!' }],
              },
            ]"
          />
        </a-form-item> -->

        <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
          <a-button type="primary" style="margin-left:100px;" html-type="submit"> {{$t('m.Ok')}} </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      :title="$t('m.DataDictionary')"
      width="1200px"
      :visible="visibleA"
      @cancel="handleCancelA"
      :footer="null"
    >
     <div style="text-align: justify;">
        <a-button
        type="primary"
        @click="adddictionaries"
        v-if="isTrue('sys:dictionaries:add')"
        style="margin-right: 15px"
        >{{ $t("m.NewDictionary") }}</a-button
      >
      <a-input-search
        :placeholder="$t('m.PleaseEnterYourSearchTerms')"
        style="width: 200px"
        enter-button
        @search="cSearch"
      />
     </div>
      <a-table
        size="small"
        style="margin-top: 20px"
        :columns="columnsA"
        :rowKey="(record, i) => i"
        :data-source="dataA"
        :pagination="false"
        bordered
      >
        <div slot="operation" slot-scope="text, tags, i">
           <a-button
            style="margin-left: 15px"
            type="primary"
            @click="editCitem(text, tags, i)"
            >{{ $t("m.Modification") }}</a-button
          >
          <a-button
            style="margin-left: 15px"
            type="danger"
            v-if="isTrue('sys:dictionaries:del')"
            @click="delcitem(text, tags, i)"
            >{{ $t("m.Delete") }}</a-button
          >

        </div>
      </a-table>
      <a-pagination
        style="margin-top: 20px"
        show-size-changer
        :default-current="1"
        :total="totalA"
        @change="PagesB"
        :pageSizeOptions="['5', '10', '30', '40']"
        @showSizeChange="onShowSizeChangeB"
        class="pages"
      />
    </a-modal>
    <a-modal
      :title="$t('m.DataDictionary')"
      :visible="visibleB"
      @cancel="handleCancelB"
      @ok="handleOkB"
      :footer="null"

    >
      <!-- {{$t('m.Code')}}<a-input v-model="forminitialC.code"
      style="width:200px;margin-bottom:20px;margin-left:20px;"/>
      <br/>
      {{$t('m.Value')}}<a-input v-model="forminitialC.name"
      style="width:200px;margin-bottom:20px;margin-left:20px;"/>
      <br/>
      {{$t('m.ExtendedAttributes1')}}
      <a-input v-model="forminitialC.attr1"
      style="width:200px;margin-bottom:20px;margin-left:20px;"/>
      <br/>
      {{$t('m.ExtendedAttributes2')}}
      <a-input v-model="forminitialC.attr2"
      style="width:200px;margin-bottom:20px;margin-left:20px;"/>
      <br/>
      {{$t('m.ExtendedAttributes3')}}
      <a-input v-model="forminitialC.attr3"
      style="width:200px;margin-bottom:20px;"/>
      <br/>
      {{$t('m.Sort')}}<a-input v-model="forminitialC.sort" style="width:200px;margin-bottom:20px;margin-left:20px;"/>
      <br/>
      {{$t('m.remark')}}<a-input v-model="forminitialC.des" style="width:200px;margin-bottom:20px;margin-left:20px;"/>
      <br/>
      {{$t('m.Vaild')}}<a-select v-model="forminitialC.status"
      default-value="1"
      style="width:100px;margin-left:20px;">
        <a-select-option value="1">
          有效
        </a-select-option>
        <a-select-option value="0">
          无效
        </a-select-option>
      </a-select> -->
      <a-form
        :form="formA"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 12 }"
        @submit="handleSubmitA"
      >
        <a-form-item :label="$t('m.Code')">
          <a-input
            v-decorator="[
              'code',
              {
                rules: [{ required: true, message: 'Please input!' }],
              },
            ]"
          />
        </a-form-item>
        <a-form-item :label="$t('m.Value')">
          <a-input
            v-decorator="[
              'name',
              {
                rules: [{ required: true, message: 'Please input!' }],
              },
            ]"
          />
        </a-form-item>
        <a-form-item :label="$t('m.ExtendedAttributes1')">
          <a-input
            v-decorator="[
              'attr1',
              {
                rules: [
                  { required: false, message: 'Please input your note!' },
                ],
              },
            ]"
          />
        </a-form-item>
        <a-form-item :label="$t('m.ExtendedAttributes2')">
          <a-input
            v-decorator="[
              'attr2',
              {
                rules: [
                  { required: false, message: 'Please input your note!' },
                ],
              },
            ]"
          />
        </a-form-item>
        <a-form-item :label="$t('m.ExtendedAttributes3')">
          <a-input
            v-decorator="[
              'attr3',
              {
                rules: [
                  { required: false, message: 'Please input!' },
                ],
              },
            ]"
          />
        </a-form-item>
        <a-form-item :label="$t('m.Sort')">
          <a-input
            v-decorator="[
              'sort',
              {
                rules: [{ required: true, message: 'Please input!' }],
              },
            ]"
          />
        </a-form-item>
        <a-form-item :label="$t('m.remark')">
          <a-input
            v-decorator="[
              'des',
              {
                rules: [
                  { required: false, message: 'Please input your note!' },
                ],
              },
            ]"
          />
        </a-form-item>
        <a-form-item :label="$t('m.Vaild')">
          <a-select
            v-decorator="[
              'status',
              {
                rules: [
                  { required: true, message: 'Please select!' },
                ],
              },
            ]"
            placeholder="Select a option and change input text above"
          >
            <a-select-option value="1"> 有效 </a-select-option>
            <a-select-option value="2"> 无效 </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
          <a-button type="primary" html-type="submit"> {{$t('m.Submit')}} </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
    <Delete :dalete="dalete" ref="unidelete" @confirm="delIsok" />
    <Delete :dalete="huadalete" ref="unideleteA" @confirm="delIsokA" />
  </div>
</template>

<script>
import Headline from "@/components/Headline";
import Delete from "@/components/Delete";
import {
  getDictionaryGroupList,
  saveDictionaryGroup,
  delDictionaryGroup,
  getDictionaryList,
  saveDictionary,
  delDictionary,
} from "@/api/systemmanagement";
import { Setperms } from "@/assets/js/setperms";
export default {
  name: "DataDictionaries",
  components: { Headline, Delete },
  data() {
    return {
      editOrAdd:true,
      personId:'',
      flag:true,
      formA: this.$form.createForm(this, { name: "coordinated" }),
      data: [],
      dalete: {
        titles: this.$t("m.DeleteThePrompt"),
        type: "exclamation-point",
        text: this.$t("m.AreYouSureToDeleteThisData"),
      },
      huadalete: {
        titles: this.$t("m.DeleteThePrompt"),
        type: "exclamation-point",
        text: this.$t("m.AreYouSureToDeleteThisData"),
      },
      columns: [
        { title: this.$t("m.Code"), dataIndex: "code" },
        { title: this.$t("m.Category"), dataIndex: "name" },
        {
          title: this.$t("m.Operation"),
          dataIndex: "tags",
          scopedSlots: { customRender: "del" },
        },
      ],
      forminitial: {
        start: 0,
        limit: 10,
        key: "",
        page: 1,
      },
      forminitialA: {
        start: 0,
        limit: 10,
        key: "",
        page: 1,
        parentCode: "",
      },
      visible: false,
      form: this.$form.createForm(this, { name: "coordinated" }),
      para: {},
      total: 0,
      visibleA: false,
      dataA: [],
      columnsA: [
        { title: this.$t("m.Code"), dataIndex: "code" },
        { title: this.$t("m.Value"), dataIndex: "name" },
        { title: this.$t("m.ExtendedAttributes1"), dataIndex: "attr1" },
        { title: this.$t("m.ExtendedAttributes2"), dataIndex: "attr2" },
        { title: this.$t("m.ExtendedAttributes3"), dataIndex: "attr3" },
        { title: this.$t("m.Sort"), dataIndex: "sort" },
        {
          title: this.$t("m.Vaild"),
          dataIndex: "status",
          customRender: function (text) {
            if (text == "1") {
              return "有效";
            } else {
              return "无效";
            }
          },
        },
        { title: this.$t("m.remark"), dataIndex: "des" },
        {
          title: this.$t("m.Operation"),
          dataIndex: "tags",
          scopedSlots: { customRender: "operation" },
        },
      ],
      visibleB: false,
      forminitialC: {
        code: "",
        name: "",
        attr1: "",
        attr2: "",
        attr3: "",
        sort: "",
        status: "1",
        des: "",
        parentCode: "",
        id: "",
      },
      totalA: 0,
      idA: "",
    };
  },
  created() {
    this.getDataClassify();
    this.parms = Setperms(
      this.$route.fullPath,
      JSON.parse(sessionStorage.getItem("menu"))
    );
    console.log(this.parms);
  },
  methods: {
    handleSubmitA(e) {
      e.preventDefault();
      this.formA.validateFields((err, values) => {
        if (!err) {
          console.log(values);
          if(this.flag == true) {
            values.parentCode = this.forminitialC.parentCode
          saveDictionary(values)
            .then((res) => {
              console.log(res);
              if (res.data.success == true) {
                this.getDataList();
                this.$message.success(res.data.msg);
              }
              if (res.data.success == false) {
                this.$message.warning(res.data.msg);
              }
              this.formA.resetFields();
            })
            .catch((err) => {
              this.$message.error("操作失败");
            });
          } else if(this.flag == false) {
            console.log('edit')
            this.forminitialC.code = values.code;
      this.forminitialC.name = values.name;
      this.forminitialC.attr1 = values.attr1;
      this.forminitialC.attr2 = values.attr2;
      this.forminitialC.attr3 = values.attr3;
      this.forminitialC.sort = values.sort;
      this.forminitialC.des = values.des;
            saveDictionary(this.forminitialC)
            .then((res) => {
              console.log(res);
              if (res.data.success == true) {
                this.getDataList();
                this.$message.success(res.data.msg);
              }
              if (res.data.success == false) {
                this.$message.warning(res.data.msg);
              }
              this.formA.resetFields();
            })
            .catch((err) => {
              this.$message.error("操作失败");
            });
          }


            this.visibleB = false;
        }
      });
    },
    isTrue(str) {
      return this.parms.indexOf(str) !== -1;
    },
    cSearch(e) {
      this.forminitialA.key = e;
      this.getDataList();
    },
    editCitem(text, tags, i) {
      this.flag = false
      this.visibleB = true;

      this.forminitialC.id = tags.id;


setTimeout(() => {
  this.formA.setFieldsValue({
    code: tags.code,
    name:tags.name,
    attr1:tags.attr1,
    attr2:tags.attr2,
    attr3:tags.attr3,
    sort:tags.sort,
    des:tags.des,
});
}, 200);

      console.log(tags);
    },
    delIsokA() {
      delDictionary({ id: this.idA })
        .then((res) => {
          if (res.data.success == true) {
            this.getDataList();
            this.$message.success(res.data.msg);
          }
          if (res.data.success == false) {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          // this.$message.error('操作失败');
          console.log(err);
        });
      this.$refs.unideleteA.visible = false;
    },
    delcitem(text, tags, i) {
      this.$refs.unideleteA.visible = true;
      this.idA = tags.id;
      console.log(tags);
    },
    adddictionaries() {
      this.visibleB = true;
      this.flag = true
    },
    onShowSizeChangeB(page, limit) {
      this.forminitialA.page = page;
      this.forminitialA.limit = limit;
      this.getDataList();
    },
    PagesB(page, pageSize) {
      this.forminitialA.limit = pageSize;
      this.forminitialA.page = page;
      this.forminitialA.start = (page - 1) * pageSize;
      this.getDataList();
    },
    handleOkB() {
      saveDictionary(this.forminitialC)
        .then((res) => {
          console.log(res);
          if (res.data.success == true) {
            this.getDataList();
            this.$message.success(res.data.msg);
          }
          if (res.data.success == false) {
            this.$message.warning(res.data.msg);
          }
        })
        .catch((err) => {
          this.$message.error("操作失败");
        });
      this.forminitialC.code = "";
      this.forminitialC.name = "";
      this.forminitialC.attr1 = "";
      this.forminitialC.attr2 = "";
      this.forminitialC.attr3 = "";
      this.forminitialC.sort = "";
      this.forminitialC.status = "";
      this.forminitialC.des = "";
      this.forminitialC.id = "";
      this.visibleB = false;
      console.log(this.forminitialC);
    },
    handleCancelB() {
      this.forminitialC.code = "";
      this.forminitialC.name = "";
      this.forminitialC.attr1 = "";
      this.forminitialC.attr2 = "";
      this.forminitialC.attr3 = "";
      this.forminitialC.sort = "";
      this.forminitialC.status = "";
      this.forminitialC.des = "";
      this.visibleB = false;
    },
    handleCancelA() {
      this.visibleA = false;
    },
    getDataList() {
      getDictionaryList({ params: this.forminitialA })
        .then((res) => {
          this.totalA = res.data.total;
          this.dataA = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    showItem(text, tags, i) {
      console.log('aa')
      this.forminitialA.page = 1
      this.forminitialA.start = 0
      this.visibleA = true;
      this.forminitialC.parentCode = JSON.parse(JSON.stringify(tags)).code;
      this.forminitialA.parentCode = JSON.parse(JSON.stringify(tags)).code;
      console.log(JSON.parse(JSON.stringify(tags)));
      this.getDataList();
    },
    delIsok() {
      this.$refs.unidelete.visible = false;
      delDictionaryGroup({ ...this.para })
        .then((res) => {
          if (res.data.success == true) {
            this.getDataClassify();
            this.$message.success(res.data.msg);
          }
          if (res.data.success == false) {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          this.$message.error("操作失败");
        });
    },
    delItem(text, tags, i) {
      this.$refs.unidelete.visible = true;
      this.para = JSON.parse(JSON.stringify(tags));
    },
    editItem(text, tags, i){
      this.editOrAdd = false
      console.log(tags)
      this.personId = tags.id
      this.visible = true;
      setTimeout(() => {
        this.form.setFieldsValue({
        code:tags.code,
        name:tags.name
      })
      }, 200);
    },
    addClassify() {
      this.editOrAdd = true
      this.visible = true;
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          if(this.editOrAdd == true) {
            saveDictionaryGroup(values)
            .then((res) => {
              if (res.data.success == true) {
                this.$message.success(res.data.msg);
                this.getDataClassify();
              }
              if (res.data.success == false) {
                this.$message.error(res.data.msg);
              }
              this.visible = false;
              this.form.resetFields()
            })
            .catch((err) => {
              this.$message.error("操作失败");
            });
          } else {
            let demo = {}
            demo = JSON.parse(JSON.stringify(values))
            demo.id = this.personId
            saveDictionaryGroup(demo)
            .then((res) => {
              if (res.data.success == true) {
                this.$message.success(res.data.msg);
                this.getDataClassify();
              }
              if (res.data.success == false) {
                this.$message.error(res.data.msg);
              }
              this.visible = false;
              this.form.resetFields()
            })
            .catch((err) => {
              this.$message.error("操作失败");
            });
          }


          console.log(values);
        }
      });
    },
    onShowSizeChange(page, limit) {
      this.forminitial.page = page;
      this.forminitial.limit = limit;
      this.getDataClassify();
    },
    Pages(page, pageSize) {
      this.forminitial.limit = pageSize;
      this.forminitial.page = page;
      this.forminitial.start = (page - 1) * pageSize;
      this.getDataClassify();
    },
    handleCancel() {
      this.visible = false;
      this.form.resetFields()
    },
    onSearch() {
      this.getDataClassify();
    },
    getDataClassify() {
      getDictionaryGroupList({ params: this.forminitial })
        .then((res) => {
          this.total = res.data.total;
          this.data = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style>
</style>
